import { GetFieldDecoratorOptions } from "antd/lib/form/Form";
import { addon, Permission } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import FormCreator, { InputType } from "src/business/components/buss-components/form-creator";
import { MainContent } from "src/business/components/style-components/main-content";
import { edit_props_info, beforeUpload } from "src/projects/app/util-tool";
import { ROUTE_PATH } from "src/projects/router";
import { AppServiceUtility } from "src/projects/app/appService";
import { isPermission } from "src/projects/app/permission";
import { remote } from 'src/projects/remote';
import { request } from "src/business/util_tool";
import { message, Card, Result, Button, Row, Steps } from "antd";
import TextArea from "antd/lib/input/TextArea";
import { NewsInfo } from "./newsInfo";
const { Step } = Steps;
/**
 * 组件：新闻编辑视图状态
 */
export interface ChangeNewsViewState extends ReactViewState {
    // 审批内容
    sp_msg?: string;
    // 是否发送
    is_send?: boolean;
    // 发布步骤
    news_step: any;
    // 申请步骤
    step?: number;
    // 状态
    status?: string;
    // 新闻内容
    news_info?: any;
    // 参数code
    paramCode?: any;
    // 参数key
    paramKey?: any;
    select_type?: any;
}

/**
 * 组件：新闻编辑视图
 * 描述
 */
export class ChangeNewsView extends ReactView<ChangeNewsViewControl, ChangeNewsViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            is_send: false,
            step: -2,
            status: '',
            news_info: [],
            news_step: [{
                'step_name': '发布',
            }, {
                'step_name': '审核',
            }, {
                'step_name': '完成',
            }],
            paramCode: this.props.match!.params.code,
            paramKey: this.props.match!.params.key,
            select_type: this.props.select_param && this.props.select_param['type'] ? this.props.select_param['type'] : '',
        };
    }
    componentDidMount() {
        const { paramKey, select_type } = this.state;
        let param: any = { id: paramKey };
        if (select_type) {
            if (select_type === 'view') {
                param['all'] = 'sh';
            } else if (select_type === 'change') {
                param['all'] = 'all';
            }
        }
        if (paramKey) {
            request(this, AppServiceUtility.article_service.get_news_list!(param, 1, 1))
                .then((datas: any) => {
                    let step_no = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['step_no']) ? datas.result[0]['new_field'][0]['step_no'] : ((datas.result && datas.result[0] && datas.result[0]['step_no']) ? datas.result[0]['step_no'] : -1);
                    let status = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['status']) ? datas.result[0]['new_field'][0]['status'] : ((datas.result && datas.result[0] && datas.result[0]['status']) ? datas.result[0]['status'] : '未知');
                    let news_info = (datas.result && datas.result[0]) ? datas.result[0] : [];
                    this.setState({
                        step: step_no,
                        status,
                        news_info,
                    });
                });
        } else {
            this.setState({
                step: 0,
                status: '待审批',
            });
        }
    }
    setRejectReason(e: any) {
        this.setState({
            sp_msg: e.target.value,
        });
    }
    setParam(step_no: number, status: string, sp_status: string, notcie: string) {
        let { sp_msg, news_info } = this.state;
        if (sp_status === '不通过' && sp_msg === '') {
            message.error('不通过请填写原因');
            return;
        }
        let param: any = {
            // 审批标识
            'is_sp': 1,
            // 审批状态
            'sp_status': sp_status,
            // 主数据状态
            'status': status,
            // 审批信息
            'sp_msg': sp_msg,
            // 步骤
            'step_no': step_no,
            // 主键ID
            'id': news_info['id'],
        };
        this.changeStatus(param, notcie);
    }
    changeStatus(value: any, notice: string) {
        const is_send = this.state.is_send;
        const that = this;
        notice = notice || '操作成功！';
        // 正在发送请求
        if (is_send === true) {
            message.error('请勿操作过快！');
            return;
        }
        this.setState(
            {
                is_send: true,
            },
            () => {
                request(that, AppServiceUtility.article_service.update_news!(value))
                    .then((data: any) => {
                        if (data === 'Success') {
                            // that.setState({
                            //     is_send: false,
                            // });
                            message.success(notice, 3, () => history.back());
                        } else {
                            message.error(data);
                        }
                    }).catch((error: Error) => {
                        message.error(error.message);
                    });
            }
        );
        return;
    }
    returnPublishForm() {
        let edit_props = {
            form_items_props: [
                {
                    title: "新闻编辑",
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.antd_input,
                            label: "新闻标题",
                            decorator_id: "title",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入新闻标题" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入新闻标题",
                            }
                        }, {
                            type: InputType.antd_input,
                            label: "新闻副标题",
                            decorator_id: "subhead",
                            field_decorator_option: {
                                rules: [{ message: "请输入新闻副标题" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入新闻副标题",
                            }
                        },
                        // {
                        //     type: InputType.radioGroup,
                        //     label: "显示状态",
                        //     decorator_id: "showing_status",
                        //     field_decorator_option: {
                        //         rules: [{ required: true, message: "请选择显示状态" }],
                        //     } as GetFieldDecoratorOptions,
                        //     option: {
                        //         options: [{
                        //             label: '首页',
                        //             value: '首页',
                        //         }, {
                        //             label: '置顶',
                        //             value: '置顶',
                        //         }]
                        //     }
                        // },
                        {
                            type: InputType.text_area,
                            label: "新闻描述",
                            decorator_id: "description",
                            field_decorator_option: {
                                rules: [{ message: "请输入新闻描述" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入新闻描述",
                            }
                        }, {
                            type: InputType.nt_rich_text,
                            label: "新闻内容",
                            decorator_id: "content",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入新闻内容" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入新闻内容",
                                value: ' '

                            }
                        },
                        {
                            type: InputType.upload,
                            label: "新闻app图片列表",
                            decorator_id: "app_img_list",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入新闻app图片列表" }],
                                initialValue: '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                action: remote.upload_url,
                                beforeUpload: beforeUpload
                            }
                        }, {
                            type: InputType.antd_input,
                            label: "作者",
                            decorator_id: "author",
                            field_decorator_option: {
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "作者"
                            }
                        }, {
                            type: InputType.antd_input,
                            label: "新闻来源",
                            decorator_id: "source",
                            field_decorator_option: {
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "新闻来源"
                            }
                        },
                    ]
                }
            ],
            other_btn_propps: [
                {
                    text: "返回",
                    cb: () => {
                        console.log("返回回调");
                        this.props.history!.push(ROUTE_PATH.newsList);
                    }
                }
            ],
            submit_btn_propps: {
                text: "保存"
            },
            service_option: {
                service_object: AppServiceUtility.article_service,
                operation_option: {
                    query: {
                        func_name: "get_news_list_all",
                        arguments: [{ id: this.props.match!.params.key }, 1, 1]
                    },
                    save: {
                        func_name: "update_news"
                    }
                },
            },
            succ_func: () => { this.props.history!.push(ROUTE_PATH.newsList); },
            id: this.props.match!.params.key,
        };
        let edit_props_list = Object.assign(edit_props, edit_props_info);
        return (
            <FormCreator {...edit_props_list} />
        );
    }
    returnInfoSH() {
        let { paramCode, news_info } = this.state;
        return (
            <Card>
                <NewsInfo news_info={news_info} />
                {paramCode ? null : <Row>
                    <br />
                    <Row>不通过请填写原因</Row>
                    <br />
                    <TextArea rows={4} onChange={(e) => { this.setRejectReason(e); }} />
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button onClick={() => this.setParam(1, '不通过', '不通过', '')}>不通过</Button>
                        <Button type="primary" onClick={() => this.setParam(2, '通过', '通过', '')}>审批通过</Button>
                        <Button onClick={() => history.back()}>返回</Button>
                    </Row>
                </Row>}
            </Card>
        );
    }
    reChange() {
        let news_step = this.state.news_step;
        news_step[0]['step_name'] = '重新编辑';
        this.setState({
            step: 1,
            select_type: 'change',
            status: '重新编辑',
            news_step,
        });
    }
    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }
        let { step, status, news_info, news_step, select_type } = this.state;
        let stepStatus: any = {};
        if (status === '不通过') {
            stepStatus.status = 'error';
        }
        // 判断是否编辑状态，步骤为1并且是编辑标识状态
        const isEditable = step === 1 && select_type === 'change';
        // step为-1代表完成了，取数组长度
        step = isEditable ? 0 : (step === -1 ? news_step.length - 1 : step);
        return (
            <MainContent>
                <Steps current={step} {...stepStatus} style={{ background: "white", padding: "25px" }}>
                    {news_step.map((item: any, index: number) => {
                        return (
                            <Step key={index} title={item.step_name} />
                        );
                    })}
                </Steps>
                {(() => {
                    if (status === '不通过') {
                        return (
                            <Card>
                                <Result
                                    status="error"
                                    title="审批不通过"
                                    subTitle={'不通过原因：' + (news_info['sp_msg'] || '暂无')}
                                />
                                <NewsInfo news_info={news_info} />
                                <Row type="flex" justify="center" className="ctrl-btns">
                                    <Button onClick={() => history.back()}>返回</Button>
                                </Row>
                            </Card>
                        );
                    } else if (status === '通过') {
                        return (
                            <Card>
                                <Result
                                    status="success"
                                    title="完成"
                                    subTitle={`审核通过！`}
                                />
                                <NewsInfo news_info={news_info} />
                                <Row type="flex" justify="center" className="ctrl-btns">
                                    <Button onClick={() => history.back()}>返回</Button>
                                    <Button onClick={() => this.reChange()}>重新编辑</Button>
                                </Row>
                            </Card>
                        );
                    } else {
                        if (isEditable || step === 0) {
                            // 申请表
                            return this.returnPublishForm();
                        } else if (step === 1) {
                            // 资料审批
                            return this.returnInfoSH();
                        }
                    }
                    return null;
                })()}
            </MainContent>
        );
    }
}

/**
 * 控件：新闻编辑视图
 * 描述
 */
@addon('ChangeNewsView', '新闻编辑视图', '描述')
@reactControl(ChangeNewsView, true)
export class ChangeNewsViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;
    /** 带参 */
    public select_param?: any;
}